﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using CP_SchoolForChildren_v0._1.Controllers.Support;
using CP_SchoolForChildren_v0._1.Models.DataModel;
using CP_SchoolForChildren_v0._1.Models.RelatedModel;

namespace CP_SchoolForChildren_v0._1.Controllers.BE
{
    public class QAManagementController : Controller
    {
        FunctionController fc = new FunctionController();
        CheckUserProfile cup = new CheckUserProfile();
        
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        #region Question

        [HttpPost]
        public JsonResult ListQuestion(string keywords, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            try
            {
                if (keywords == null)
                    keywords = "";
                //Get Data
                var record = from qa in fc.db.Questions
                             join us in fc.db.Users on qa.UserID equals us.UserID
                             where qa.QuestionContent.Contains(keywords)
                             select new
                                        {
                                            QuestionID = qa.QuestionID,
                                            QuestionContent = qa.QuestionContent,
                                            CreatedTime = qa.CreatedTime,
                                            UserName = us.UserName,
                                            AnswerCount = qa.Answers.Count
                                        };
                //Get Total row
                var totalrow = record.Count();

                //Paging
                var temp = record.OrderUsingSortExpression(jtSorting).Skip(jtStartIndex).Take(jtPageSize);

                return Json(new {Result = "OK", Records = temp.ToList(), TotalRecordCount = totalrow});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", ex.Message});
            }
        }

        [HttpPost]
        public JsonResult CreateQuestion(Question question)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Dữ liệu nhập vào không đúng"
                                    });
                }
                question.UserID = fc.CurrentUserID(User.Identity.Name);
                question.CreatedTime = DateTime.Now;
                fc.db.Questions.Add(question);
                var record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        // Edit question : NOT ALLOW
        //[HttpPost]
        //public JsonResult UpdateQuestion(Question question)
        //{
        //    try
        //    {
        //        if (!ModelState.IsValid)
        //        {
        //            return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
        //        }

        //        using (var db = new SFCEntities())
        //        {
        //            fc.db.Configuration.ProxyCreationEnabled = false;
        //            fc.db.Entry(question).State = System.Data.EntityState.Modified;
        //            var record = fc.db.SaveChanges();
        //            return Json(new { Result = "OK", Record = record });
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return Json(new { Result = "ERROR", Message = ex.ToString() });
        //    }
        //}

        [HttpPost]
        public JsonResult DeleteQuestion(Question question)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }
                DeleteQuestionFK(question);
                fc.db.Entry(question).State = EntityState.Deleted;
                var record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", ex.Message});
            }
        }

        //Delete all answer
        public void DeleteQuestionFK(Question question)
        {
            try
            {
                List<Answer> aw = fc.db.Answers.Where(a => a.QuestionID == question.QuestionID).ToList();
                foreach (Answer tmp in aw)
                {
                    fc.db.Answers.Remove(tmp);
                }
                fc.db.SaveChanges();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        #endregion

        #region Answer

        [HttpPost]
        public JsonResult ListAnswer(int QuestionID, string keywords, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            try
            {
                if (keywords == null)
                    keywords = "";

                var record = from a in fc.db.Answers
                             join us in fc.db.Users on a.UserID equals us.UserID
                             where a.AnswerContent.Contains(keywords)
                             where a.QuestionID == QuestionID
                             select new
                                        {
                                            a.QuestionID,
                                            a.AnswerID,
                                            a.AnswerContent,
                                            a.CreatedTime,
                                            us.UserName
                                        };
                var totalrow = record.Count();

                var temp = record.OrderUsingSortExpression(jtSorting).Skip(jtStartIndex).Take(jtPageSize);

                return Json(new {Result = "OK", Records = temp.ToList(), TotalRecordCount = totalrow});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", ex.Message});
            }
        }

        [HttpPost]
        public JsonResult CreateAnswer(Answer answer)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Form is not valid! " +
                                                  "Please correct it and try again."
                                    });
                }
                answer.UserID = fc.CurrentUserID(User.Identity.Name);

                fc.db.Answers.Add(answer);
                int record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [HttpPost]
        public JsonResult UpdateAnswer(Answer answer)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }

                using (var db = new SFCEntities())
                {
                    fc.db.Entry(answer).State = EntityState.Modified;
                    int record = fc.db.SaveChanges();
                    return Json(new {Result = "OK", Record = record});
                }
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", ex.Message});
            }
        }

        [HttpPost]
        public JsonResult DeleteAnswer(Answer answer)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }
                fc.db.Entry(answer).State = EntityState.Deleted;
                int record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", ex.Message});
            }
        }

        #endregion
    }
}